package com.jinpin.oauth.service.impl;

import com.jinpin.core.enums.ResultEnum;
import com.jinpin.core.result.ResultUtil;
import com.jinpin.oauth.entity.LoginUser;
import com.jinpin.oauth.entity.User;
import com.jinpin.oauth.service.LoginService;
import com.jinpin.redis.tran.RedisFile;
import com.jinpin.redis.utils.RedisUtil;
import com.jinpin.security.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public ResultUtil login(User user) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(token);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //  jtw密钥生成
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String jwt = JwtUtil.createJWT(loginUser.getUsername());
        // todo 把用户权限放入redis
        redisUtil.setCacheObject(RedisFile.USER+loginUser.getUsername(), loginUser.getPermissions(),3L, TimeUnit.DAYS);

        Map<String, Object> map = new HashMap<>();
        map.put("token", jwt);
        map.put("token_type", "Bearer ");
        return new ResultUtil(ResultEnum.LOGIN_SUCCESS.getCode(),ResultEnum.LOGIN_SUCCESS.getMsg(),map);
    }


}
